<template>
	<el-upload class="avatar-uploader" :action="action" :show-file-list="false" :on-success="handleAvatarSuccess"
	 :before-upload="beforeAvatarUpload" :data="uploadKey">
		<img v-if="image" :src="image" class="avatar">
		<i v-else class="el-icon-plus avatar-uploader-icon"></i>
	</el-upload>
</template>

<script>
	import {
		reactive,
		ref,
		watch,
		onMounted,
	} from '@vue/composition-api';
	export default {
		/* 
		‘组件形成过程’要做什么  七牛云token--显示默认图片，渲染图片 
		
		 最终结果要做什么  返回图片路径----最终路径提交
		 */
		name: "uploadImg",
		props: {
			imageUrl: {    //双向的 
				type: String,
				default: ""
			}
		},
		setup(props, {
			root,
			emit
		}) {
			const uploadKey = reactive({
				token: '',
				key: ''
			})
			const image = ref('')
			const action = root.$store.state.common.action
			// mounted
			onMounted(() => {
				root.$store.dispatch('common/getToken')
			})
			// 方法 
			const handleAvatarSuccess = (res, file) => {
				// 这里需要处理路径我艹 老师的token不能用 所以传不了
				// 前面一部分是路径 后面拼接的是图片的名字  后端也可以完全返回 
				// image.value = `${root.$store.getters["common/qiniuUrl"]}${res.key}`
				emit('update:imageUrl', image.value)
			}
			const beforeAvatarUpload = (file) => {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					root.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					root.$message.error('上传头像图片大小不能超过 2MB!');
				}
				// 文件名转码 + 存token一起传上去
				let suffix = file.name
				let key = encodeURI(`${suffix}`)
				uploadKey.key = key
				uploadKey.token = root.$store.state.common.token
				return isJPG && isLt2M;
			}
			// 监听
			watch(() => props.imageUrl, (val) => {
				image.value = val
			})
			return {
				uploadKey,
				image,
				action,
				handleAvatarSuccess,
				beforeAvatarUpload
			}
		}


	}
</script>


<style lang='scss' scoped>




</style>
